<template>
    <div ref="container" class="preview-container"></div>
</template>

<script setup lang="ts">
import 'jquery'
import { onMounted, ref, watch } from 'vue'
import { JBoltApi } from '@/utils'

interface Props {
    /** 模板sn*/
    templateSn: string
    /** 用于渲染的数据来源url */
    dataUrl?: string
    /** 用于渲染的数据 */
    data?: object
}

const props = withDefaults(defineProps<Props>(), {})

const hiprintTemplate = ref()

//json
const templateData = ref()

const container = ref<HTMLElement>()

async function loadData() {
    //获取模板内容
    const { result: templateResult } = await JBoltApi.post(
        `/api/admin/hiprint/tpl/content?sn=${props.templateSn}`
    )
    //获取模板Json
    if (props.dataUrl) {
        const { result: res } = await JBoltApi.post(props.dataUrl)
        templateData.value = res.data
    } else {
        templateData.value = props.data
    }

    hiprintTemplate.value = new hiprint.PrintTemplate({
        template: JSON.parse(templateResult.data)
    })
    if (hiprintTemplate.value) {
        let html = hiprintTemplate.value.getHtml(templateData.value)
        container.value!.innerHTML = html.html()
    }
}

watch(
    () => props,
    () => {
        loadData()
    },
    {
        deep: true
    }
)

onMounted(() => {
    loadData()
})

function print(clientPrint = false) {
    // 参数: 打印时设置 左偏移量，上偏移量
    let options = { leftOffset: -1, topOffset: -1 }
    // 扩展
    let ext = {
        callback: () => {
            console.log('浏览器打印窗口已打开')
        },
        styleHandler: () => {}
    }
    // 调用浏览器打印
    if (clientPrint) {
        hiprintTemplate.value.print2(templateData.value, options, ext)
    } else {
        hiprintTemplate.value.print(templateData.value, options, ext)
    }
}

function toPdf(name = '文件') {
    hiprintTemplate.value?.toPdf(templateData.value, name)
}

defineExpose({
    print,
    toPdf
})
</script>

<style scoped lang="scss"></style>
